package net.eascn.dao
{
	import com.adobe.utils.XMLUtil;
	import com.adobe.xml.syndication.atom.Atom10;
	import com.youbt.events.RFLoaderEvent;
	import com.youbt.manager.RFResourceManager;
	import com.youbt.net.RFURLLoader;
	
	import mx.controls.Alert;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.mxml.HTTPService;
	
	import net.eascn.model.ModelLocator;

	public class Provider
	{
		
		private const  baseURL:String =  "http://picasaweb.google.com/data/feed/base/user/";
		private var _service:HTTPService = null;
		
		static private var _instance:Provider = null;
		static public function getInstance():Provider
		{
			if(!_instance)
				_instance = new Provider();
			return _instance;
		}
		
		public function Provider()
		{
			init();
		}
		
		protected function init():void{
			_service = new HTTPService();
			_service.showBusyCursor = true;
			_service.resultFormat = 'text';
			_service.addEventListener(ResultEvent.RESULT,onResult);
			_service.addEventListener(FaultEvent.FAULT,onFault);
			
		}
		
		protected function onFault(event:FaultEvent):void
		{
			Alert.show(event.fault.faultDetail);
		}
		protected function onResult(event:ResultEvent):void
		{
			var data:String = String(event.result);
			if(!com.adobe.utils.XMLUtil.isValidXML(data))
			{
				Alert.show('xml falut');
				return;
			}
			var rss2:Atom10  =   new Atom10();
			rss2.parse(data);
			var items:Array = rss2.entries;

			//loop through each item in the feed
			for each(var item:Object  in items)
			{
				ModelLocator.getInstance().albums.addItem(item);
			}
			ModelLocator.getInstance().seletIndex =1;
		}
		
		
		
		public function getUserAlbumListFeed($username:String):void
		{
			var url:String = baseURL+$username+'??thumbsize=32';
			_service.url = url;
			_service.send();		
		}
		
		public function test($u:String):void
		{
			var url:String = baseURL+$u+'??thumbsize=32';
			var loader:RFURLLoader = new RFURLLoader(url,url);
			loader.addEventListener(RFLoaderEvent.PROGRESS,onProgress);
			loader.addEventListener(RFLoaderEvent.FAILED,onProgress);
			loader.addEventListener(RFLoaderEvent.COMPLETE,onProgress);
			loader.load();
		}
		
		private function onProgress(event:RFLoaderEvent):void
		{
			switch(event.type)
			{
				case RFLoaderEvent.COMPLETE:
					RFResourceManager.Save(event.url,event.result);
				break;
				case RFLoaderEvent.FAILED:
					Alert.show('fault');
				break;
				case RFLoaderEvent.PROGRESS:
					ModelLocator.getInstance().percent = -1;
				break;
			}
		}
		
		public function getUserAlbumByID($idstr:String):void
		{
			_service.url = $idstr;
			_service.send();
		}
		
		
	}
}